<script setup lang="js">
import {ref, onMounted, watch} from 'vue';
import {Search, Tickets} from "@element-plus/icons-vue";
import {fetchReturnApplyList, deleteApply} from "@/api/returnApply.js";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";

const router = useRouter();
onMounted(() => {
  getReturnApplyList();
});
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  id: null,
  receiverKeyword: null,
  status: null,
  createTime: null,
  handleMan: null,
  handleTime: null
};
const defaultStatusOptions = [
  {
    label: '待处理',
    value: 0
  },
  {
    label: '退货中',
    value: 1
  },
  {
    label: '已完成',
    value: 2
  },
  {
    label: '已拒绝',
    value: 3
  }
];
const listQuery = Object.assign({}, defaultListQuery)
const statusOptions = Object.assign({}, defaultStatusOptions)
const orderSearch = ref({})

// TODO: 格式化订单创建时间
const formatDate = (date) => {
  // 检查是否为 Date 对象
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}



// TODO: 格式化订单状态
const formatStatus = (status) => {
  for (let i = 0; i < defaultStatusOptions.length; i++) {
    if (status === defaultStatusOptions[i].value) {
      return defaultStatusOptions[i].label;
    }
  }
}
const total = ref(0)
const returnApplyList = ref([])

// TODO: 获取数据列表
const getReturnApplyList = async () => {
  const res = await fetchReturnApplyList(listQuery)
  console.log(res.data.data.list)
  returnApplyList.value = res.data.data.list
  total.value = res.data.data.total
}

// TODO: 查询搜索
const handleSearch = () => {
  listQuery.pageNum = 1
  getReturnApplyList()
}
// TODO: 重置搜索
const handleResetSearch = () => {
  listQuery.id = null
  listQuery.receiverKeyword = null
  listQuery.status = null
  listQuery.createTime = null
  listQuery.handleMan = null
  listQuery.handleTime = null
  orderSearch.value = {}
  getReturnApplyList()
}

// TODO: 表单选择数目
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
}


// TODO: 查看详情
const handleViewOrder = (row) => {
  router.push({path: '/detail/return/applyDetail',
    query: {
      id: row.id
    }
  })
}


// TODO: 监听订单数据
watch(() => listQuery, (newVal) => {
      orderSearch.value = newVal
    },
    {immediate: true}
)

// TODO: 批量操作
const operateType = ref(1)
const operateOperations = [
  {label: '批量删除', value: 1},
]
const handleBatchOperate = () => {
  if (multipleSelection.value === null || multipleSelection.value.length <1) {
    ElMessage.warning('请选择要操作的申请')
  } else {
    if (operateType.value === 1) {
     let params = new URLSearchParams()
      let ids = []
      for (let i = 0; i < multipleSelection.value.length; i++) {
        ids.push(multipleSelection.value[i].id)
      }
      params.append('ids', ids)
      deleteApply(params).then((res) => {
        ElMessage.warning(res.data.message)
        ElMessage.success('删除成功')
        getReturnApplyList()
      }).catch(() => {
        ElMessage.error('删除失败')
      })
    }
  }
}


// TODO: 页码改变
const handleCurrentChange = (currentPage) => {
  listQuery.pageNum = currentPage
  getReturnApplyList()
}
// TODO: 页码大小改变
const handleSizeChange = (pageSize) => {
  listQuery.pageSize = pageSize
  listQuery.pageNum = 1
  getReturnApplyList()
}

</script>

<template>
  <div class="return-application">
    <!-- 顶部搜索区域-->
    <div class="top-bar">
      <div class="logo">
        <div class="logo-text">
          <el-icon>
            <Search/>
          </el-icon>
          <span>筛选搜索</span>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="handleSearch()">查询结果</el-button>
          <el-button icon="refresh" @click="handleResetSearch()">重置</el-button>
        </div>
      </div>
      <div class="search">
        <el-form :inline="true" v-model="orderSearch" label-width="100px">
          <el-form-item label="输入搜索：">
            <el-input v-model="orderSearch.id" class="input-width" placeholder="订单编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="处理状态：">
            <el-select v-model="orderSearch.status" class="input-width" placeholder="请选择" clearable>
              <el-option v-for="item in statusOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间：">
            <el-date-picker
                v-model="orderSearch.createTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="MMM DD, YYYY"
                time-format="HH:mm"
                placeholder="请选择时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="操作人员：">
            <el-input v-model="orderSearch.handleMan" class="input-width"
                      placeholder="收货人姓名/手机号码" clearable></el-input>
          </el-form-item>
          <el-form-item label="处理时间：">
            <el-date-picker
                v-model="orderSearch.handleTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="MMM DD, YYYY"
                time-format="HH:mm"
                placeholder="请选择时间">
            </el-date-picker>
          </el-form-item>


        </el-form>
      </div>
    </div>
    <!-- 中部添加按钮 -->
    <div class="center-bar">
      <div class="add-btn">
        <el-icon>
          <Tickets/>
        </el-icon>
        <span>数据列表</span>
      </div>
    </div>
    <!-- 底部列表区域 -->
    <div class="bottom-bar">
      <el-table :data="returnApplyList" style="width: 100%;" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="100" align="center"></el-table-column>
        <el-table-column label="服务单号" width="150" align="center">
          <template #default="{row}">{{ row.id }}</template>
        </el-table-column>
        <el-table-column label="申请时间" width="" align="center">
          <template #default="{row}">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="用户账号" width="200" align="center">
          <template #default="{row}">
            {{ row.memberUsername }}
          </template>
        </el-table-column>
        <el-table-column label="退款金额" width="200" align="center">
          <template #default="{row}">
            ￥{{ row.productRealPrice * row.productCount }}
          </template>
        </el-table-column>
        <el-table-column label="申请状态" align="center">
          <template #default="{row}">
            {{ formatStatus(row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="处理时间" align="center">
          <template #default="{row}">
            {{ formatDate(row.handleTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-button type="primary" icon="pointer" @click="handleViewOrder(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部分页 -->
    <div class="page-bar">
      <div class="select-type">
        <span>批量操作：</span>
        <el-select v-model="operateType" placeholder="请选择操作">
          <el-option
              v-for="item in operateOperations"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        <el-popconfirm
            placement="top"
            confirm-button-text="确定"
            cancel-button-text="取消"
            title="确认删除？"
            @confirm="handleBatchOperate">
          <template #reference>
            <el-button type="danger" icon="delete">批量删除</el-button>
          </template>
        </el-popconfirm>
      </div>
      <el-pagination
          background
          layout="total, sizes,prev, pager, next,jumper"
          :total="total"
          :page-sizes="[5,10,15,20]"
          v-model:page-size="listQuery.pageSize"
          v-model:current-page="listQuery.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<style scoped lang="scss">
.return-application {
  height: 100%;
  display: flex;
  flex-direction: column;

  .top-bar {
    //height: 100px;
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;

    .logo {
      width: 100%;
      font-size: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        margin: 0 8px;
      }

      .search-btn {
        padding: 0 10px;
      }
    }

    .search {
      width: 100%;

      .el-form {
        margin-top: 20px;

        .el-form-item {
          width: 280px;
        }
      }
    }
  }

  .center-bar {
    //height: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;

    .add-btn {
      display: flex;
      align-items: center;

      span {
        margin-left: 8px;
        font-size: 18px;
      }
    }
  }

  .page-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;
    padding: 10px 20px;

    .select-type {
      width: 400px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .el-select {
        margin-right: 20px;
      }
    }

    span {
      width: 180px;
    }
  }

}

</style>
